/*
 * @Author: Wxx
 * @Date: 2022-02-24 15:52:24
 * @LastEditors: Wxx
 * @LastEditTime: 2022-02-26 16:40:25
 * @Description:
 */
import React, { Component } from "react";
import { Route, Redirect, Switch } from "react-router-dom";
import Center from "../views/Center";
import Films from "../views/Films";
import Cinemas from "../views/Cinemas";
import NotFound from "../views/NotFound";
import Detail from "../views/Detail";
import Login from "../views/Login";
import { withRouter } from "react-router-dom/cjs/react-router-dom.min";
import { includes } from "lodash";
import store from "../redux/store";
import { showTabbar, hideTabbar } from "../redux/actionCreator/TabbarCreator";
import City from "../views/City";
import Search from "../views/Search";
class router extends Component {
  state = {};
  static getDerivedStateFromProps(nextProps) {
    const path = nextProps.location.pathname;
    const show = includes(
      ["/films/comingsoon", "/films/nowplaying", "/cinemas", "/center"],
      path
    );
    setTimeout(() => {
      if (show) {
        store.dispatch(showTabbar());
      } else {
        store.dispatch(hideTabbar());
      }
    }, 0);

    return null;
  }

  isAuth = () => {
    return localStorage.getItem("token");
  };
  render() {
    return (
      <div>
        <Switch>
          <Route path="/films" component={Films} />
          <Route path="/cinemas" component={Cinemas} exact />
          <Route path="/cinemas/search" component={Search} />
          <Route
            path="/center"
            render={(props) => {
              // 路由拦截 如果没有登录就重定向跳转到登录页面
              // 这里如果没有把props传给center 通过render出来的路由页面是获取不到
              // 路由的相关信息 可以通过withRouter来包裹组件，可以拿到路由相关信息
              return this.isAuth() ? (
                <Center />
              ) : (
                <Redirect from="center" to="login" />
              );
            }}
          />
          <Route path="/login" component={Login} />
          <Route path="/city" component={City} />
          {/* 动态路由 可以在组件的props的match拿到参数 */}
          {/* <Route path="/detail/:id" component={Detail} /> */}
          <Route path="/detail" component={Detail} />
          {/* 如果域名后没有跟路径 会重定向到films页面 加了exact 就变成了精确匹配 */}
          <Redirect from="/" to="/films" exact />
          <Route component={NotFound} />
        </Switch>
        {this.props.children}
      </div>
    );
  }
}

export default withRouter(router);
